<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getDialogTitle()"
    :fullscreen="true"
    :before-close="handleClose"
    class="process-detail-modal"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
  >
    <div class="detail-container">
      <!-- Tab导航 -->
      <el-card class="tab-card">
        <el-tabs v-model="activeTab" class="detail-tabs">
          
          <!-- 表单详情 -->
          <el-tab-pane label="表单详情" name="form" v-if="showFormTab">
            <FormDetail 
              :key="`form-${displayData?.processInstanceId || displayData?.id || Date.now()}-${formDataKey}`"
              ref="formDetailRef"
              :form-data="dataManager.getData().formData"
              :process-data="displayData"
              :mode="props.mode"
              :editable="isStartMode || isTaskMode"
              @form-action="handleFormAction"
              @form-data-change="handleFormDataChange"
            />
          </el-tab-pane>
          
          <!-- 流程图 -->
          <el-tab-pane label="流程图" name="diagram" v-if="showDiagramTab">
            <div v-if="!dataManager.getData().diagramLoaded" class="diagram-loading">
              <el-empty description="正在加载流程图..." />
            </div>
            <ProcessDiagram
              v-else
              :key="`diagram-${displayData?.processInstanceId || displayData?.id || Date.now()}`"
              :process-data="displayData"
              :graph-data="dataManager.getData().graphData"
              :loading="false"
              :node-status-list="dataManager.getData().nodeStatusList"
              :gateway-conditions="getGatewayConditions()"
              @refresh="handleRefresh"
              @node-click="handleNodeDetail"
            />
          </el-tab-pane>
          
          <!-- 流程详情（仅在非发起模式显示） -->
          <el-tab-pane label="流程详情" name="detail" v-if="showDetailTab">
            <ProcessDetail
              :key="`detail-${displayData?.processInstanceId || displayData?.id || Date.now()}`"
              :display-data="displayData"
              :node-status-list="dataManager.getData().nodeStatusList"
              :approval-history="dataManager.getData().approvalHistory"
              :mode="props.mode"
              @node-detail="handleNodeDetail"
            />
          </el-tab-pane>
          
          <!-- 流程配置（仅在发起模式显示） -->
          <el-tab-pane label="流程配置" name="config" v-if="showConfigTab">
            <ApprovalOperation
              :key="`config-${displayData?.processId || displayData?.id || Date.now()}`"
              ref="approvalOperationRef"
              :process-data="displayData"
              :task-data="null"
              :graph-data="dataManager.getData().graphData"
              :is-start-mode="true"
              :form-data="dataManager.getData().formData"
              :next-nodes="dataManager.getData().nextNodes"
              :personnel-edit-permission="getProcessEditPermission()"
              @approval-action="handleApprovalAction"
              @start-process="handleStartProcessFromApproval"
            />
          </el-tab-pane>
          
          <!-- 审批操作（仅任务处理模式显示） -->
          <el-tab-pane label="审批操作" name="approval" v-if="showApprovalTab">
            <ApprovalOperation
              :key="`approval-${displayData?.processInstanceId || displayData?.id || Date.now()}`"
              :process-data="displayData"
              :task-data="displayData"
              :graph-data="dataManager.getData().graphData"
              :form-data="dataManager.getData().formData"
              :next-nodes="dataManager.getData().nextNodes"
              :is-start-mode="false"
              :personnel-edit-permission="getProcessEditPermission()"
              @approval-action="handleApprovalAction"
            />
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <!-- 移除发起流程按钮，只在流程配置区域内保留 -->
        <el-button 
          v-if="showRefreshButton" 
          type="primary" 
          @click="handleRefresh"
        >
          刷新
        </el-button>
        <!-- 全屏模式下添加退出全屏按钮 -->
        <el-button 
          type="info" 
          @click="handleClose"
          icon="Close"
        >
          退出全屏
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 节点详情弹窗 -->
  <NodeDetailModal
    v-model:visible="nodeDetailVisible"
    :node-data="selectedNodeData"
    :show-process-button="isTaskMode"
    @process="handleNodeProcess"
    @close="nodeDetailVisible = false"
  />
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import FormDetail from './components/FormDetail.vue'
import ProcessDetail from './components/ProcessDetail.vue'
import ProcessDiagram from './components/ProcessDiagram.vue'
import NodeDetailModal from './components/NodeDetailModal.vue'
import ApprovalOperation from './components/ApprovalOperation.vue'
import { processDetailDataManager } from './utils/processDetailDataManager'
import { calculateGatewayConditions } from './utils/gatewayConditionCalculator'

// 引入统一的夜间模式样式
import './styles/dark-theme.css'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  processData: {
    type: Object,
    default: null
  },
  taskData: {
    type: Object,
    default: null
  },
  mode: {
    type: String,
    default: 'view', // view: 查看模式, start: 发起模式, task: 任务处理模式
    validator: (value) => ['view', 'start', 'task'].includes(value)
  }
})

const emit = defineEmits(['update:visible', 'start-process', 'form-action', 'process-success'])

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// Tab控制 - 默认显示表单详情
const activeTab = ref('form')

// 设置默认Tab
const setDefaultTabByMode = () => {
  if (isStartMode.value) {
    // 发起流程模式：默认显示表单详情
    activeTab.value = 'form'
  } else if (isTaskMode.value) {
    // 任务处理模式：默认显示审批操作
    activeTab.value = 'approval'
  } else if (isViewMode.value) {
    // 查看模式：默认显示流程详情
    activeTab.value = 'process'
  }
}

watch(() => props.mode, (newMode, oldMode) => {
  setDefaultTabByMode()
})

watch(() => props.visible, (visible, oldVisible) => {
  if (visible) {
    setDefaultTabByMode()
  }
})

// 子组件ref
const formDetailRef = ref()
const approvalOperationRef = ref()

// 数据管理器
const dataManager = processDetailDataManager

// 节点详情相关
const selectedNodeData = ref(null)
const nodeDetailVisible = ref(false)

// 表单数据key，用于强制重新渲染
const formDataKey = ref(0)

// 初始化标志，防止重复初始化
const isInitializing = ref(false)

// 统一的初始化方法
const initializeModalData = async () => {
  if (isInitializing.value) {
    return
  }
  
  if (!props.visible || !displayData.value) {
    return
  }
  
  isInitializing.value = true
  
  try {
    // 先重置数据管理器
    dataManager.resetData()
    
    // 重置FormDetail组件状态
    if (formDetailRef.value) {
      formDetailRef.value.resetForm()
    }
    
    // 初始化数据
    await dataManager.initializeData(displayData.value, props.mode)
  } catch (error) {
    console.error('ProcessDetailModal - initialization failed:', error)
  } finally {
    isInitializing.value = false
  }
}

// 计算属性 - 模式判断
const isViewMode = computed(() => props.mode === 'view')
const isStartMode = computed(() => props.mode === 'start')
const isTaskMode = computed(() => props.mode === 'task')

// 计算属性 - Tab显示控制
const showFormTab = computed(() => true) // 所有模式都显示表单详情
const showDiagramTab = computed(() => true) // 所有模式都显示流程图
const showDetailTab = computed(() => !isStartMode.value) // start模式不显示流程详情
const showConfigTab = computed(() => isStartMode.value) // 只有start模式显示流程配置
const showApprovalTab = computed(() => isTaskMode.value) // 只有task模式显示审批操作

// 计算属性 - 按钮显示控制
const showRefreshButton = computed(() => isViewMode.value || isTaskMode.value)

// 计算属性 - 数据源
const displayData = computed(() => {
  const result = isTaskMode.value ? props.taskData : props.processData
  return result
})

// 初始化数据管理器
onMounted(() => {
  dataManager.setCallbacks({
    onDataChange: (data) => {
      // 数据变化时的回调
      // 强制更新FormDetail组件
      if (data.formData) {
        // 增加key值，强制重新渲染FormDetail组件
        formDataKey.value++
        // 使用nextTick确保DOM更新
        nextTick(() => {
          // 触发FormDetail组件的重新渲染
          if (formDetailRef.value) {
            formDetailRef.value.resetForm()
          }
        })
      }
    },
    onSuccess: (action, result) => {
      if (action === 'start-process') {
        emit('start-process', result)
        handleClose()
      } else if (action === 'submit-approval') {
        emit('process-success')
        handleClose()
      }
    },
    onError: (action, error) => {
      console.error(`${action} failed:`, error)
    }
  })
})

// 处理审批操作
const handleApprovalAction = async (action, data) => {
  
  if (action === 'start-process') {
    // 处理发起流程
    try {
      // 先进行表单校验
      if (formDetailRef.value && typeof formDetailRef.value.validateForm === 'function') {
        const validationResult = await formDetailRef.value.validateForm()
        
        if (!validationResult.valid) {
          // 校验失败，显示错误信息
          const errorMessage = validationResult.errors && validationResult.errors.length > 0 
            ? validationResult.errors.join('; ') 
            : '表单数据校验失败，请检查必填项'
          ElMessage.error(errorMessage)
          console.error('ProcessDetailModal - 表单校验失败:', validationResult.errors)
          return
        }
        
      } else {
        console.warn('ProcessDetailModal - FormDetail组件没有validateForm方法')
      }
      
      const formData = await getFormDataFromModal()
      
      const assigneeConfig = await getAssigneeConfigFromModal()
      
      await dataManager.startProcess(displayData.value, formData, assigneeConfig)
    } catch (error) {
      console.error('ProcessDetailModal - 流程发起失败:', error)
    }
  } else if (action === 'submit') {
    // 处理任务审批提交
    try {
      await dataManager.submitApproval(displayData.value, data)
    } catch (error) {
      console.error('ProcessDetailModal - 审批提交失败:', error)
    }
  }
}

// 处理从ApprovalOperation组件发出的start-process事件
const handleStartProcessFromApproval = async (data) => {
  
  try {
    // 先进行表单校验
    if (formDetailRef.value && typeof formDetailRef.value.validateForm === 'function') {
      const validationResult = await formDetailRef.value.validateForm()
      
      if (!validationResult.valid) {
        // 校验失败，显示错误信息
        const errorMessage = validationResult.errors && validationResult.errors.length > 0 
          ? validationResult.errors.join('; ') 
          : '表单数据校验失败，请检查必填项'
        ElMessage.error(errorMessage)
        console.error('ProcessDetailModal - 表单校验失败:', validationResult.errors)
        return
      }
      
    } else {
      console.warn('ProcessDetailModal - FormDetail组件没有validateForm方法')
    }
    
    const result = await dataManager.startProcess(displayData.value, data.formData, data.assigneeConfig)
    
    // 流程发起成功后，关闭弹窗并通知父组件
    ElMessage.success('流程发起成功')
    emit('start-process', { success: true, data: displayData.value })
    handleClose()
  } catch (error) {
    console.error('ProcessDetailModal - 流程发起失败:', error)
    ElMessage.error('流程发起失败: ' + error.message)
  }
}

// 处理表单操作
const handleFormAction = (action, data) => {
  emit('form-action', action, data)
}

// 处理表单数据变化
const handleFormDataChange = (newFormData) => {
  
  // 检查是否是事件对象，如果是则忽略
  if (newFormData && typeof newFormData === 'object' && newFormData.target && newFormData.type) {
    return
  }
  
  // 确保是有效的表单数据
  if (newFormData && typeof newFormData === 'object') {
    // 更新表单数据
    if (dataManager.getData().formData) {
      dataManager.getData().formData.formData = newFormData
    } else {
      dataManager.getData().formData = { formData: newFormData }
    }
    
    // 通知数据管理器数据变化，触发网关条件重新计算
    dataManager.onFormDataChange(newFormData)
  }
}

// 处理节点详情
const handleNodeDetail = async (nodeData) => {
  
  // 如果传入的是流程图节点数据，需要找到对应的节点状态数据
  let nodeStatusData = nodeData
  
  // 检查是否是流程图节点数据（通常包含id、type、position等属性）
  if (nodeData && (nodeData.id || nodeData.type) && dataManager.getData().nodeStatusList.length > 0) {
    // 尝试通过节点ID或名称匹配节点状态数据
    const nodeStatusList = dataManager.getData().nodeStatusList
    
    // 优先通过节点ID匹配
    if (nodeData.id) {
      const matchedByNodeId = nodeStatusList.find(status => 
        status.nodeId === nodeData.id || 
        status.taskDefinitionKey === nodeData.id ||
        status.taskId === nodeData.id
      )
      if (matchedByNodeId) {
        nodeStatusData = matchedByNodeId
      }
    }
    
    // 如果通过ID没找到，尝试通过节点名称匹配
    if (nodeStatusData === nodeData && nodeData.data?.label) {
      const matchedByName = nodeStatusList.find(status => 
        status.nodeName === nodeData.data.label ||
        status.taskName === nodeData.data.label
      )
      if (matchedByName) {
        nodeStatusData = matchedByName
      }
    }
    
    // 如果通过名称也没找到，尝试通过节点类型匹配（增强版）
    if (nodeStatusData === nodeData && nodeData.type) {
      // 创建类型映射表
      const typeMapping = {
        'start': ['startEvent', 'START_EVENT', 'start'],
        'end': ['endEvent', 'END_EVENT', 'end'],
        'task': ['userTask', 'USER_TASK', 'task'],
        'gateway': ['exclusiveGateway', 'EXCLUSIVE_GATEWAY', 'gateway'],
        'parallelGateway': ['parallelGateway', 'PARALLEL_GATEWAY'],
        'inclusiveGateway': ['inclusiveGateway', 'INCLUSIVE_GATEWAY'],
        'serviceTask': ['serviceTask', 'SERVICE_TASK'],
        'subProcess': ['subProcess', 'SUB_PROCESS']
      }
      
      const targetTypes = typeMapping[nodeData.type] || [nodeData.type]
      const matchedByType = nodeStatusList.find(status => 
        targetTypes.includes(status.nodeType) ||
        targetTypes.includes(status.taskType) ||
        targetTypes.includes(status.type)
      )
      if (matchedByType) {
        nodeStatusData = matchedByType
      }
    }
    
    // 如果通过类型也没找到，尝试通过节点标签匹配（针对流程图节点）
    if (nodeStatusData === nodeData && nodeData.data?.label) {
      const label = nodeData.data.label
      const matchedByLabel = nodeStatusList.find(status => {
        // 检查节点名称是否包含标签关键词
        const nodeName = status.nodeName || status.taskName || ''
        return nodeName.includes(label) || label.includes(nodeName)
      })
      if (matchedByLabel) {
        nodeStatusData = matchedByLabel
      }
    }
    
    // 如果还是没找到，尝试通过节点位置或顺序匹配
    if (nodeStatusData === nodeData) {
      // 对于开始节点，通常排在第一位
      if (nodeData.type === 'start' && nodeStatusList.length > 0) {
        const startNode = nodeStatusList.find(status => 
          status.nodeType === 'startEvent' || 
          status.taskType === 'startEvent' ||
          status.nodeName?.includes('开始')
        )
        if (startNode) {
          nodeStatusData = startNode
        }
      }
      // 对于结束节点，通常排在最后一位
      else if (nodeData.type === 'end' && nodeStatusList.length > 0) {
        const endNode = nodeStatusList.find(status => 
          status.nodeType === 'endEvent' || 
          status.taskType === 'endEvent' ||
          status.nodeName?.includes('结束')
        )
        if (endNode) {
          nodeStatusData = endNode
        }
      }
    }
    
    // 如果还是没找到匹配的节点状态数据，为未开始的节点组装数据
    if (nodeStatusData === nodeData) {
      
      // 根据节点类型组装未开始的节点数据
      const nodeLabel = nodeData.data?.label || nodeData.id || '未知节点'
      const nodeType = nodeData.type || 'unknown'
      
      // 组装未开始的节点数据
      nodeStatusData = {
        nodeName: nodeLabel,
        nodeType: getNodeTypeFromFlowType(nodeType),
        taskType: getNodeTypeFromFlowType(nodeType),
        status: 'PENDING', // 未开始状态
        assignee: null,
        userName: null,
        approver: null,
        startTime: null,
        endTime: null,
        createTime: null,
        completeTime: null,
        duration: null,
        description: `未开始的${getNodeTypeText(nodeType)}节点`,
        taskId: null,
        taskDefinitionKey: nodeData.id,
        nodeId: nodeData.id
      }
      
    }
  }
  
  selectedNodeData.value = nodeStatusData
  nodeDetailVisible.value = true
}

// 根据流程图节点类型获取标准节点类型
const getNodeTypeFromFlowType = (flowType) => {
  const typeMapping = {
    'start': 'startEvent',
    'end': 'endEvent',
    'task': 'userTask',
    'gateway': 'exclusiveGateway',
    'parallelGateway': 'parallelGateway',
    'inclusiveGateway': 'inclusiveGateway',
    'serviceTask': 'serviceTask',
    'subProcess': 'subProcess'
  }
  return typeMapping[flowType] || flowType
}

// 获取节点类型文本
const getNodeTypeText = (nodeType) => {
  const typeMap = {
    'start': '开始',
    'end': '结束',
    'task': '任务',
    'gateway': '网关',
    'parallelGateway': '并行网关',
    'inclusiveGateway': '包容网关',
    'serviceTask': '服务任务',
    'subProcess': '子流程'
  }
  return typeMap[nodeType] || nodeType
}

// 处理节点任务
const handleNodeProcess = (nodeData) => {
  ElMessage.info('任务处理功能待实现')
}

// 刷新数据
const handleRefresh = async () => {
  await dataManager.refreshAllData(displayData.value, props.mode)
  ElMessage.success('数据已刷新')
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  
  // 重置数据管理器
  dataManager.resetData()
  
  // 重置FormDetail组件状态
  if (formDetailRef.value) {
    formDetailRef.value.resetForm()
  }
  
  // 重置tab状态
  activeTab.value = 'form'
}

// 从弹窗获取表单数据
const getFormDataFromModal = async () => {
  try {
    if (formDetailRef.value) {
      const formData = await formDetailRef.value.getFormData()
      return formData
    }
    return {}
  } catch (error) {
    return {}
  }
}

// 从弹窗获取人员配置
const getAssigneeConfigFromModal = async () => {
  try {
    if (approvalOperationRef.value) {
      const assigneeConfig = await approvalOperationRef.value.getAssigneeConfig()
      if (assigneeConfig && assigneeConfig.length > 0) {
        return assigneeConfig
      }
      return []
    }
    return []
  } catch (error) {
    console.error('获取人员配置失败:', error)
    return []
  }
}

// 获取弹窗标题
const getDialogTitle = () => {
  let title = '流程详情'
  
  if (displayData.value) {
    if (displayData.value.processName) {
      title = `${displayData.value.processName} - 流程详情`
    } else if (displayData.value.name) {
      title = `${displayData.value.name} - 流程详情`
    }
  }
  
  // 根据模式添加后缀
  if (isStartMode.value) {
    title += ' (发起模式)'
  } else if (isTaskMode.value) {
    title += ' (任务处理)'
  }
  
  return title
}

// 获取流程编辑权限
const getProcessEditPermission = () => {
  // 从流程数据中获取编辑权限配置
  // 优先级：任务数据 > 流程数据 > 默认值
  const editPermission = displayData.value?.personnelEditPermission || 
                        displayData.value?.advanced?.personnelEditPermission ||
                        props.processData?.advanced?.personnelEditPermission ||
                        'full'
  
  return editPermission
}

// 监听流程数据变化
watch(() => displayData.value, (newData, oldData) => {
  // 避免重复初始化，只在数据真正变化时初始化
  if (newData && props.visible && newData !== oldData) {
    nextTick(() => {
      initializeModalData()
      
      // 延迟获取网关条件数据，确保ApprovalOperation组件已经更新
      setTimeout(() => {
        const gatewayConditions = getGatewayConditions()
      }, 200)
    })
  }
}, { immediate: false }) // 移除 immediate: true，避免在组件初始化时执行

// 监听弹窗显示状态
watch(() => props.visible, (visible, oldVisible) => {
  
  if (visible && !oldVisible) { // 只在弹窗打开时初始化，避免重复
    nextTick(() => {
      initializeModalData()
    })
    
    // 添加全屏模式下的快捷键支持
    document.addEventListener('keydown', handleKeydown)
  } else if (!visible && oldVisible) {
    // 弹窗关闭时移除快捷键监听
    document.removeEventListener('keydown', handleKeydown)
  }
}, { immediate: false }) // 移除 immediate: true，避免重复初始化

// 全屏模式下的快捷键处理
const handleKeydown = (event) => {
  // ESC键关闭弹窗
  if (event.key === 'Escape') {
    handleClose()
  }
  // Ctrl+R 刷新数据
  if (event.ctrlKey && event.key === 'r') {
    event.preventDefault()
    if (showRefreshButton.value) {
      handleRefresh()
    }
  }
}

// 移除重复的监听器，避免重复调用
// 监听任务数据变化，确保数据更新时能重新初始化
// watch(() => props.taskData, (newTaskData) => {
//   console.log('ProcessDetailModal - taskData changed:', newTaskData)
//   if (newTaskData && props.visible) {
//     console.log('ProcessDetailModal - reinitializing data due to taskData change...')
//     dataManager.resetData()
//     nextTick(() => {
//       dataManager.initializeData(newTaskData, props.mode)
//     })
//   }
// }, { immediate: false })

// 监听流程数据变化，确保数据更新时能重新初始化
// watch(() => props.processData, (newProcessData) => {
//   console.log('ProcessDetailModal - processData changed:', newProcessData)
//   if (newProcessData && props.visible) {
//     console.log('ProcessDetailModal - reinitializing data due to processData change...')
//     dataManager.resetData()
//     nextTick(() => {
//       dataManager.initializeData(newProcessData, props.mode)
//     })
//   }
// }, { immediate: false })

// 监听tab切换，实现数据懒加载
watch(() => activeTab.value, (newTab) => {
  if (newTab === 'diagram' && !dataManager.getData().diagramLoaded) {
    // 只在第一次切换到流程图tab且数据未加载时，加载流程图数据
    dataManager.loadDiagramData(displayData.value)
  }
}, { immediate: false })

// 获取网关条件数据
const getGatewayConditions = () => {
  
  // 优先从ApprovalOperation组件中获取网关条件数据
  if (approvalOperationRef.value && typeof approvalOperationRef.value.getGatewayConditions === 'function') {
    try {
      const gatewayConditions = approvalOperationRef.value.getGatewayConditions()
      return gatewayConditions
    } catch (error) {
      console.error('ProcessDetailModal - 获取网关条件数据失败:', error)
    }
  }
  
      // 如果ApprovalOperation组件不可用，从数据管理器中获取nextNodes数据并推断网关条件
    const nextNodes = dataManager.getData().nextNodes
    const formData = dataManager.getData().formData
    if (nextNodes && nextNodes.length > 0 && formData) {
      
      try {
        // 获取实际的表单数据（用户填写的表单值）
        let actualFormData = formData
        if (formData && typeof formData === 'object' && formData.formData) {
          actualFormData = formData.formData
        }
        
        
        // 使用公共方法计算网关条件
        const gatewayConditions = calculateGatewayConditions(nextNodes, actualFormData)
        if (gatewayConditions.length > 0) {
          return gatewayConditions
        }
      } catch (error) {
        console.error('ProcessDetailModal - 使用nextNodes计算网关条件失败:', error)
      }
    }
    
    // 如果从nextNodes无法获取网关条件，尝试从nodeStatusList推断
    const nodeStatusList = dataManager.getData().nodeStatusList
    const graphData = dataManager.getData().graphData
    if (nodeStatusList && nodeStatusList.length > 0 && graphData) {
      
      try {
        // 使用新的网关条件计算方式
        const gatewayConditions = calculateGatewayConditions(nodeStatusList, graphData, formData)
        return gatewayConditions
      } catch (error) {
        console.error('ProcessDetailModal - 从nodeStatusList推断网关条件失败:', error)
      }
    }
  
  return []
}

// 暴露方法给父组件
defineExpose({
  getFormData: getFormDataFromModal,
  getAssigneeConfig: getAssigneeConfigFromModal,
  getGatewayConditions
})
</script>

<style scoped>
.process-detail-modal {
  /* 全屏弹窗样式 */
}

/* 确保弹窗能正确显示 */
:deep(.el-dialog) {
  z-index: 9999 !important;
}

/* 全屏弹窗内容区域样式 */
:deep(.el-dialog__body) {
  padding: 20px;
  height: calc(100vh - 160px); /* 减去头部和底部的高度，为流程图留出更多空间 */
  overflow-y: auto;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f8f9fa;
}

:deep(.el-dialog__footer) {
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  background-color: #f8f9fa;
}

.detail-container {
  height: 100%;
  overflow-y: auto;
}

.tab-card {
  margin-bottom: 20px;
  height: calc(100% - 20px);
}

.detail-tabs {
  height: 100%;
}

:deep(.el-tabs__content) {
  height: calc(100% - 55px) !important; /* 减去tab标签的高度 */
  overflow-y: auto;
  padding: 20px 0;
}

:deep(.el-tab-pane) {
  height: 100% !important;
  min-height: 600px;
}

/* 流程图Tab的特殊高度处理 */
:deep(.el-tab-pane[name="diagram"]) {
  min-height: calc(100vh - 300px) !important; /* 确保流程图有足够的最小高度 */
  height: calc(100vh - 300px) !important; /* 强制设置高度 */
}

/* 优化Tab标签样式 */
:deep(.el-tabs__header) {
  margin-bottom: 0;
  background-color: #f8f9fa;
  border-radius: 4px 4px 0 0;
}

:deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.dialog-footer {
  text-align: right;
}

/* 流程图相关样式 */
.diagram-loading {
  min-height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 流程图容器样式 - 确保高度与弹窗一致 */
:deep(.el-tab-pane[name="diagram"]) {
  height: 100% !important;
  display: flex !important;
  flex-direction: column !important;
  min-height: calc(100vh - 300px) !important;
}

/* 流程图标题样式 */
:deep(.el-tab-pane[name="diagram"] h3) {
  margin: 0 0 15px 0;
  padding: 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

/* 流程图画布容器样式 */
:deep(.el-tab-pane[name="diagram"] .process-diagram-container) {
  flex: 1 !important;
  height: calc(100% - 50px) !important;
  min-height: calc(100vh - 350px) !important;
  overflow: hidden;
}

/* 确保流程图组件能够正确填充高度 */
:deep(.el-tab-pane[name="diagram"] .vue-flow) {
  height: 100% !important;
  width: 100% !important;
  min-height: calc(100vh - 400px) !important;
}

:deep(.el-tab-pane[name="diagram"] .vue-flow__viewport) {
  height: 100% !important;
  width: 100% !important;
}

/* 强制流程图Tab内容区域高度 */
:deep(.el-tab-pane[name="diagram"] .diagram-content) {
  height: 100% !important;
  min-height: calc(100vh - 350px) !important;
}

:deep(.el-tab-pane[name="diagram"] .flow-diagram) {
  height: 100% !important;
  min-height: calc(100vh - 350px) !important;
}

/* 调试样式 - 为流程图Tab添加明显的边框和背景 */
:deep(.el-tab-pane[name="diagram"]) {
  border: 2px solid #ff6b6b !important;
  background-color: rgba(255, 107, 107, 0.1) !important;
}

/* 全屏弹窗的响应式调整 */
@media (max-width: 768px) {
  :deep(.el-dialog__body) {
    padding: 15px;
    height: calc(100vh - 140px);
  }
  
  :deep(.el-dialog__header) {
    padding: 15px;
  }
  
  :deep(.el-dialog__footer) {
    padding: 15px;
  }
  
  /* 移动端流程图高度调整 */
  :deep(.el-tab-pane[name="diagram"]) {
    min-height: calc(100vh - 250px);
  }
}

/* 大屏幕优化 */
@media (min-width: 1920px) {
  :deep(.el-dialog__body) {
    height: calc(100vh - 180px);
  }
  
  :deep(.el-tab-pane[name="diagram"]) {
    min-height: calc(100vh - 350px);
  }
}
</style>